import { defineStore } from 'pinia'
import { WorkApi } from '@/api/works'
import { type ListData } from 'axios'

/**
 * 模板列表
 * @methods setTemplatesList 设置模板数据
 */
export const workInfos = defineStore('works', {
  state: (): WorksProp => ({
    templates: [],
    works: [],
    totalWorks: 0,
    statics: [],
    totalTemplates: 0,
    searchText: ''
  }),
  actions: {
    async setWorkList(params: any) {
      const { pageIndex, title } = params
      const [e, r] = await WorkApi.getWorks<ListData<WorkProp>>(params, {
        opName: 'getWorks'
      })
      if (r && r.errno === 0) {
        const { count, list } = r.data
        if (pageIndex === 0) {
          this.works = list
        } else {
          this.works = [...this.works, ...list]
        }
        this.totalWorks = count
        this.searchText = title || ''
      }
    },
    async setTempList(params: any) {
      const { pageIndex, searchText } = params
      const [e, r] = await WorkApi.getTemplates<ListData<WorkProp>>(params, {
        opName: 'getTemplates'
      })
      if (r && r.errno === 0) {
        const { count, list } = r.data
        if (pageIndex === 0) {
          this.templates = list
        } else {
          this.templates = [...this.templates, ...list]
        }
        this.totalTemplates = count
        this.searchText = searchText || ''
      }
    },
    async createWork(payload: {}) {
      let ndata
      const [e, r] = await WorkApi.createWork<WorkProp>(payload, {
        opName: 'createWork'
      })
      if (r && r.errno === 0) {
        this.works.unshift(r.data)
        ndata = r.data
      }
      return ndata
    },
    async deleteWork(id: number) {
      const [e, r] = await WorkApi.deleteWork<WorkProp>(id, {
        opName: 'deleteWork'
      })
      if (r && r.errno === 0) {
        this.works = this.works.filter((work) => work.id !== id)
      }
    },
    async fetchTemplate(id: number) {
      const [e, r] = await WorkApi.getWork<WorkProp>(id, {
        opName: 'getWork'
      })
      if (r && r.errno === 0) {
        this.templates = [r.data]
      }
    }
  },
  getters: {
    getTemplateById: (state) => {
      return (id: number) => state.templates.find((t) => t.id === id)
    }
  }
})
